# -*- coding: utf-8 -*-
import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pythonblog.model.content import *
from pythonblog.lib.base import BaseController, render
from pythonblog.service import content_service 
from pythonblog.service import user_service
import pythonblog.lib.helpers as h
from pylons.decorators import jsonify

log = logging.getLogger(__name__)

class CommentController(BaseController):

    @jsonify
    def create(self, id):
        try:
            id = long(id)
            if not content_service.is_post_exist(id):
                abort(404)
            userInfo = u'匿名'
            comment = Comment()
            comment.content = request.params['content']
            comment.post_id = id
            if request.environ.has_key('REMOTE_USER'):
                user = user_service.get_user(request.environ['REMOTE_USER'])
                comment.user_id = user.id
                userInfo = '<a target="_blank" href="%s">%s</a>' % \
                  (h.url_for('home', sub_domain=user.userName), user.author)
            meta.Session.add(comment)        
            meta.Session.commit()
            content_service.add_comment_to_cache(comment)
            import datetime
            return { 'flag': 1, 'userInfo': userInfo, 'createDate': datetime.datetime.strftime(comment.createDate, "%Y-%m-%d %H:%M:%S") } 
        except:
            import sys
            return { 'flag': 0, 'info': sys.exc_info()[1] }

